//
//  SyncDataManager.m
//  clublbiza
//
//  Created by WANG TOM on 7/21/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SyncDataManager.h"
#import "ASIHTTPRequest.h"
#import "JSON.h"
#import "ApiLogin.h"
#import "TMDataTable.h"
#import "Resource.h"



@implementation SyncDataManager
@synthesize tableName;

-(SyncDataManager *) initWithTableName:(NSString *) ptableName {
    [super init];
    self.tableName = ptableName;
    return  self;
}
-(void) dealloc
{
    self.tableName = nil;
    [super dealloc];
}
-(void) syncData
{
     ApiLogin *apiLogin = [ApiLogin shareInstance];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *defaultKey = [NSString stringWithFormat:@"tbl_current_version_%@",self.tableName];
    NSInteger currentVersionNumber = [userDefaults integerForKey:defaultKey];
  
    AppMain *appMain = [AppMain shareInstance];
    NSURL *url = [NSURL URLWithString:[[appMain getGateWayURL:NO] stringByAppendingFormat:@"a=getdata&tbName=%@&version=%d&sid=%@",self.tableName,currentVersionNumber,apiLogin.session_id]];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSString *response_str = [request responseString];
        id response_obj = [response_str JSONValue];
        if(nil != response_obj && [response_obj isKindOfClass:[NSDictionary class]]){
            id error_obj = [response_obj objectForKey:@"error"];
            if([error_obj length] == 0){
                NSArray *records_data_list = [response_obj objectForKey:@"data"];
                [self processDataHandler:records_data_list];
            }else if([error_obj isEqualToString:@"need login"]) {
               
                [apiLogin login];
                [self syncData];
                NSLog(@"Call login action then load data again");
                
            }else{
                NSException* exception = [NSException
                                          exceptionWithName:@"API_ERROR"
                                          reason:[error_obj localizedDescription]
                                          userInfo:nil];
                @throw exception;
            }
        }
        
    } else{
        NSException* exception = [NSException
                                  exceptionWithName:@"API_ERROR"
                                  reason:[error localizedDescription]
                                  userInfo:nil];
        @throw exception;
    }
}

-(void) processDataHandler:(NSArray *)dataList
{
    if ( [dataList count] == 0 ) {
        return;
    }
    if ( [self.tableName isEqualToString:@"delete_record_log"] ) {
        [self processDeleteRecord:dataList];
    }else{
        [self processUpdateRecord:dataList];
    }
}
-(void) processDeleteRecord:(NSArray *)dataList
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *defaultKey = [NSString stringWithFormat:@"tbl_current_version_%@",self.tableName];
    
    if ([userDefaults objectForKey:defaultKey] == nil) {
        NSString *maxVersionNumber = [dataList.lastObject objectForKey:@"version_id"];
        [userDefaults setInteger:[maxVersionNumber integerValue] forKey:defaultKey];
    }
    for(NSDictionary *row_obj in dataList ) {
        NSString *loc_tableName = [row_obj objectForKey:@"table_name"];
        NSString *loc_pkvalue = [row_obj objectForKey:@"uuid"];
        
        //uppercase the first character

        loc_tableName = [loc_tableName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[loc_tableName substringToIndex:1] uppercaseString]];
        
        TMDataTable *dt = [[TMDataTable alloc] initWithTablename:loc_tableName withPKName:@"uuid" contextProvider:[ApiLogin shareInstance]];
     
        
        //delete resource file
        if ([loc_tableName isEqualToString:@"Resource"]) {
             NSFileManager *fileManager = [NSFileManager defaultManager];
            Resource *exist_resource_data = (Resource*)[dt find:loc_pkvalue];
            if ( nil != exist_resource_data)
            {
            NSString *recource_name = exist_resource_data.path;
            NSString *filePath = [[AppMain resourceFolderPath] stringByAppendingFormat:@"/%@",recource_name];
            NSError *error = nil;
         
                if (![fileManager removeItemAtPath:filePath error:&error])
                {
                    NSLog(@"Error removing file: %@", error); 
                }
            }
        }
        
        [dt deleteRow:loc_pkvalue];
    }
    
    NSString *maxVersionNumber = [dataList.lastObject objectForKey:@"version_id"];
    
    
    [userDefaults setInteger:[maxVersionNumber integerValue] forKey:defaultKey];
}
-(void) processUpdateRecord:(NSArray *)dataList
{
    TMDataTable *dt = [[TMDataTable alloc] initWithTablename:self.tableName withPKName:@"uuid" contextProvider:[ApiLogin shareInstance]];
    [dt saveRows:dataList];
    NSString *maxVersionNumber = [dataList.lastObject objectForKey:@"version_id"];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *defaultKey = [NSString stringWithFormat:@"tbl_current_version_%@",self.tableName];
    
    [userDefaults setInteger:[maxVersionNumber integerValue] forKey:defaultKey];
    
    [dt release];
    
}
@end
